﻿using HealthcareSystem.API.Read.Application.Command.ChronicDisease;
using HealthcareSystem.API.Read.DTO.ChronicDTO;
using HealthcareSystem.Domain;
using HealthcareSystem.Domain.ChronicDiseaseManagement;
using MediatR;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel.ChronicDisease
{
    public class HealthReportListCommandHandler : IRequestHandler<HealthReportListCommand, ApiResult<ApiPaging<List<HealthReportDTO>>>>
    {
        private readonly IBaseRepository<HealthReport> hrRepository;
        private readonly IBaseRepository<Login> loginRepository;

        public HealthReportListCommandHandler(IBaseRepository<HealthReport> hrRepository, IBaseRepository<Login> loginRepository)
        {
            this.hrRepository = hrRepository;
            this.loginRepository = loginRepository;
        }

        public Task<ApiResult<ApiPaging<List<HealthReportDTO>>>> Handle(HealthReportListCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<List<HealthReportDTO>>> result = new ApiResult<ApiPaging<List<HealthReportDTO>>>();
            result.Code = ResultCode.查询成功;
            result.Message = ResultCode.查询成功.ToString();

            var list = from a in hrRepository.GetAll() 
                       join b in loginRepository.GetAll() on a.UserId equals b.UserId
                       where !a.IsDelete
                       select new HealthReportDTO 
                       {
                           ReportId = a.ReportId,
                           ReportType = a.ReportType,
                           CreateTime = a.CreateTime,
                           ReportingPeriod = a.ReportingPeriod,
                           ReleaseStatus = a.ReleaseStatus,
                           IsDelete = a.IsDelete,
                           UserId = b.UserId,
                           UserNickname = b.UserNickname,
                       };
            if (!string.IsNullOrEmpty(request.ReportType))
            {
                list = list.Where(x => x.ReportType.Contains(request.ReportType));
            }
            var totalCount = list.Count();
            var totalPage = (int)Math.Ceiling((totalCount * 1.0) / request.PageSize);
            list = list.OrderByDescending(x => x.ReportId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            ApiPaging<List<HealthReportDTO>> paging = new ApiPaging<List<HealthReportDTO>>();
            paging.totalPage = totalPage;
            paging.totalCount = totalCount;
            paging.Data = list.ToList();
            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
